<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\RoleResource;
use Illuminate\Http\Request;
use App\Role;
use Spatie\Permission\Models\Permission;

class RoleController extends Controller
{
    /**
     * 获取角色列表
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $roles = Role::latest()->with('permissions')->paginate($request->get('per_page', 10));
        return RoleResource::collection($roles);
    }

    /**
     * 新增角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|min:2',
            'display_name' => 'required|min:2',
        ]);
        $role = Role::updateOrCreate(['id' => $request->get('id', ' ')], $request->all());
        return response()->json($role);
    }

    /**
     * 修改角色权限
     */
    public function changePermissionToRole(Request $request, Role $role)
    {
        $this->validate($request, [
            'permission_id' => "array"
        ],
            [
                'permission_id.array' => '权限id必须为数组'
            ]
        );
        $role->syncPermissions($request->get('permission_id', []));
        return response()->json(['status' => 200, 'message' => 'success']);
    }
    public function destroy(Request $request, Role $role)
    {
        $role->delete();
        return response()->json(['status' => 200, 'message' => '删除成功']);
    }

    //通过角色获取菜单列表
    public function menus(Request $request, Role $role)
    {
        $menus = $role->menus();
        return response()->json($menus);
    }

    //获取角色拥有的菜单
    public function getMenusToRole(Request $request, Role $role)
    {
        $role->load('menus');
        return new RoleResource($role);
    }
}
